from scrapy import FormRequest, Spider, cmdline, Request
from Phoneband.untils.utils_log import log, log_out
from Phoneband.items import PhonebandItem
import json


class DeliStoreSpider(Spider):
    name = 'deli_store'
    allowed_domains = ['nbdeli.com']
    start_urls = ['https://www.nbdeli.com/products/lists/0?type=37']
    custom_settings = {
        'DEFAULT_REQUEST_HEADERS': {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "en,zh-CN;q=0.9,zh;q=0.8",
            "Cache-Control": "max-age=0",
            "Connection": "keep-alive",
            # "Cookie": "euid=bdba2a7f2aebb7b4df66f49f53ba81816f2fb270127775a7; CSRF-TOKEN=A839FEE54F2BE5A1AD230CC7D5507D3F0A8CEC1D9EB3E5D7; cps_id=119884; cps_direct=1; deviceid=b0133a654690f44cdf481e94971e29c6; TID=b0133a654690f44cdf481e94971e29c6; salePortal=1; HWWAFSESID=80d291305302609539a; HWWAFSESTIME=1604717329791; _areacode=CN; locale_MS=zh_CN; cps_track_id=1604717351723_m5rgpcg1jl",
            # "Host": "openapi.vmall.com",
            # "CsrfToken": "A839FEE54F2BE5A1AD230CC7D5507D3F0A8CEC1D9EB3E5D7",
            # "Upgrade-Insecure-Requests": "1",
        }
    }

    def parse(self, response):
        products = response.xpath("//div[@class='item col-sm-3 col-xs-6']/div/a/@href")
        for product in products:
            item = PhonebandItem()
            url = product.extract()
            item['url'] = url
            log('url', url)
            yield Request(url=url, callback=self.parse_detail, meta={'item': item})
            break

    def parse_detail(self, response):
        item = response.meta['item']
        proinfo = response.xpath("//div[@class='proinfo f-cb']")
        img = proinfo.xpath("/div[1]//div[@class='swiper-slide swiper-slide-active']//img/@src")
        right = proinfo.xpath("/div[2]")
        title = right.xpath("/div[@class='tit']").extract()

        # 'id': id,
        # 'title': phone[i]['name'],
        # 'url': 'https://www.vmall.com/product/' + str(phone[i]['productId']) + '.html',
        # 'price': phone[i]['price'],
        # 'imgs': '["https://res.vmallres.com/pimages/{}428_428_{}"]'.format(phone[i]['photoPath'], phone[i][
        #     'photoName']),
        # 'desc': phone[i]['skuName'],
        # 'shop_name': '华为官方',

        # //div[@class='proinfo f-cb']/div[1]//div[@class='swiper-slide swiper-slide-active']//img/@src
        log('proinfo', proinfo)
        # log('img', img)

